#include "clienthandler.h"
#include <QDataStream>
#include <QJsonArray>
#include <QDebug>
#include <QSqlQuery>

ClientHandler::ClientHandler(qintptr socketDescriptor, QObject *parent)
    : QThread(parent), m_socketDescriptor(socketDescriptor), 
      m_socket(nullptr), m_currentUserId(-1), m_currentUserRole(-1) {
}

ClientHandler::~ClientHandler() {
    if (m_socket) {
        m_socket->deleteLater();
    }
}

void ClientHandler::disconnectFromClient() {
    try {
        if (m_socket && m_socket->isOpen()) {
            m_socket->disconnectFromHost();
        }
        quit();
        wait();
    } catch (const std::exception& e) {
        qDebug() << "断开客户端连接异常:" << e.what();
        quit();
    } catch (...) {
        qDebug() << "断开客户端连接未知异常";
        quit();
    }
}

void ClientHandler::run() {
    try {
        m_socket = new QTcpSocket();
        
        if (!m_socket->setSocketDescriptor(m_socketDescriptor)) {
            qDebug() << "无法设置套接字描述符";
            return;
        }
        
        connect(m_socket, &QTcpSocket::readyRead, this, &ClientHandler::onReadyRead, Qt::DirectConnection);
        connect(m_socket, &QTcpSocket::disconnected, this, &ClientHandler::onDisconnected, Qt::DirectConnection);
        
        qDebug() << "客户端处理线程启动";
        exec();
    } catch (const std::exception& e) {
        qDebug() << "客户端线程异常:" << e.what();
    } catch (...) {
        qDebug() << "客户端线程未知异常";
    }
}

void ClientHandler::onReadyRead() {
    try {
        if (!m_socket || !m_socket->isOpen()) {
            return;
        }
        
        m_buffer.append(m_socket->readAll());
        
        // 处理可能的多个消息
        while (m_buffer.size() >= 4) {
            // 读取消息长度
            QDataStream stream(&m_buffer, QIODevice::ReadOnly);
            stream.setVersion(QDataStream::Qt_5_0);
            
            quint32 messageSize;
            stream >> messageSize;
            
            // 检查消息大小是否合理（防止恶意数据）
            if (messageSize > 10 * 1024 * 1024) {  // 最大10MB
                qDebug() << "消息过大，断开连接";
                m_socket->disconnectFromHost();
                return;
            }
            
            // 检查是否接收到完整消息
            if (m_buffer.size() < 4 + messageSize) {
                break;
            }
            
            // 提取消息数据
            QByteArray messageData = m_buffer.mid(4, messageSize);
            m_buffer.remove(0, 4 + messageSize);
            
            // 解析消息
            MessageType type;
            QJsonObject data;
            if (Protocol::parseMessage(messageData, type, data)) {
                processMessage(type, data);
            } else {
                qDebug() << "解析消息失败";
            }
        }
    } catch (const std::exception& e) {
        qDebug() << "处理客户端数据异常:" << e.what();
        m_buffer.clear();  // 清空缓冲区
    } catch (...) {
        qDebug() << "处理客户端数据未知异常";
        m_buffer.clear();
    }
}

void ClientHandler::onDisconnected() {
    try {
        qDebug() << "客户端断开连接";
        emit disconnected(this);
        quit();
    } catch (const std::exception& e) {
        qDebug() << "处理断开连接异常:" << e.what();
        quit();
    } catch (...) {
        qDebug() << "处理断开连接未知异常";
        quit();
    }
}

void ClientHandler::processMessage(MessageType type, const QJsonObject& data) {
    try {
        qDebug() << "处理消息类型:" << type;
    
    switch (type) {
        case MSG_LOGIN:
            handleLogin(data);
            break;
        case MSG_REGISTER:
            handleRegister(data);
            break;
        case MSG_GET_PATIENT_INFO:
            handleGetPatientInfo(data);
            break;
        case MSG_UPDATE_PATIENT_INFO:
            handleUpdatePatientInfo(data);
            break;
        case MSG_MAKE_APPOINTMENT:
            handleMakeAppointment(data);
            break;
        case MSG_CANCEL_APPOINTMENT:
            handleCancelAppointment(data);
            break;
        case MSG_GET_APPOINTMENTS:
            handleGetAppointments(data);
            break;
        case MSG_GET_APPOINTMENT_DETAIL:
            handleGetAppointmentDetail(data);
            break;
        case MSG_GET_MEDICAL_RECORDS:
            handleGetMedicalRecords(data);
            break;
        case MSG_GET_PRESCRIPTIONS:
            handleGetPrescriptions(data);
            break;
        case MSG_GET_DOCTOR_INFO:
            handleGetDoctorInfo(data);
            break;
        case MSG_UPDATE_DOCTOR_INFO:
            handleUpdateDoctorInfo(data);
            break;
        case MSG_GET_DOCTOR_SCHEDULE:
            handleGetDoctorSchedule(data);
            break;
        case MSG_GET_PATIENT_LIST:
            handleGetPatientList(data);
            break;
        case MSG_CREATE_MEDICAL_RECORD:
            handleCreateMedicalRecord(data);
            break;
        case MSG_CREATE_PRESCRIPTION:
            handleCreatePrescription(data);
            break;
        case MSG_CREATE_EXAM_REQUEST:
            handleCreateExamRequest(data);
            break;
        case MSG_GET_DEPARTMENTS:
            handleGetDepartments(data);
            break;
        case MSG_GET_DOCTORS_BY_DEPT:
            handleGetDoctorsByDept(data);
            break;
        case MSG_PAYMENT:
            handlePayment(data);
            break;
        case MSG_GET_PAYMENT_HISTORY:
            handleGetPaymentHistory(data);
            break;
        case MSG_START_CONSULTATION:
            handleStartConsultation(data);
            break;
        case MSG_FINISH_CONSULTATION:
            handleFinishConsultation(data);
            break;
        case MSG_CHECK_APPOINTMENT_COMPLETION:
            handleCheckAppointmentCompletion(data);
            break;
        case MSG_GET_ALL_DOCTORS:
            handleGetAllDoctors(data);
            break;
        case MSG_GET_CHAT_PATIENTS:
            handleGetChatPatients(data);
            break;
        case MSG_SEND_MESSAGE:
            handleSendMessage(data);
            break;
        case MSG_GET_CHAT_HISTORY:
            handleGetChatHistory(data);
            break;
        case MSG_GET_UNREAD_COUNT:
            handleGetUnreadCount(data);
            break;
        case MSG_MARK_AS_READ:
            handleMarkAsRead(data);
            break;
        case MSG_GET_NOTIFICATIONS:
            handleGetNotifications(data);
            break;
        case MSG_CLEAR_ALL_NOTIFICATIONS:
            handleClearAllNotifications(data);
            break;
        case MSG_ATTENDANCE_CHECKIN:
            handleAttendanceCheckIn(data);
            break;
        case MSG_ATTENDANCE_CANCEL:
            handleAttendanceCancel(data);
            break;
        case MSG_GET_ATTENDANCE_RECORDS:
            handleGetAttendanceRecords(data);
            break;
        case MSG_GET_TODAY_ATTENDANCE:
            handleGetTodayAttendance(data);
            break;
        case MSG_CREATE_LEAVE_REQUEST:
            handleCreateLeaveRequest(data);
            break;
        case MSG_CANCEL_LEAVE_REQUEST:
            handleCancelLeaveRequest(data);
            break;
        case MSG_GET_LEAVE_REQUESTS:
            handleGetLeaveRequests(data);
            break;
        case MSG_CANCEL_LEAVE:
            handleCancelLeave(data);
            break;
        case MSG_GET_POPULAR_MEDICINES:
            handleGetPopularMedicines(data);
            break;
        case MSG_SEARCH_MEDICINES:
            handleSearchMedicines(data);
            break;
        default:
            qDebug() << "未知的消息类型:" << type;
            break;
    }
    } catch (const std::exception& e) {
        qDebug() << "处理消息异常:" << e.what() << "消息类型:" << type;
    } catch (...) {
        qDebug() << "处理消息未知异常，消息类型:" << type;
    }
}

void ClientHandler::sendResponse(MessageType type, const QJsonObject& data) {
    try {
        if (!m_socket || !m_socket->isOpen()) {
            qDebug() << "Socket已关闭，无法发送响应";
            return;
        }
        
        QByteArray message = Protocol::createMessage(type, data);
        m_socket->write(message);
        m_socket->flush();
    } catch (const std::exception& e) {
        qDebug() << "发送响应异常:" << e.what();
    } catch (...) {
        qDebug() << "发送响应未知异常";
    }
}

void ClientHandler::handleLogin(const QJsonObject& data) {
    QString username = data["username"].toString();
    QString password = data["password"].toString();
    
    User user;
    if (DatabaseManager::instance().authenticateUser(username, password, user)) {
        m_currentUserId = user.id;
        m_currentUserRole = user.role;
        
        QJsonObject response = user.toJson();
        response["success"] = true;
        sendResponse(MSG_LOGIN_RESPONSE, response);
        
        qDebug() << "用户登录成功:" << username;
    } else {
        QJsonObject response = Protocol::createErrorResponse("用户名或密码错误");
        sendResponse(MSG_LOGIN_RESPONSE, response);
        qDebug() << "用户登录失败:" << username;
    }
}

void ClientHandler::handleRegister(const QJsonObject& data) {
    User user = User::fromJson(data);
    
    if (DatabaseManager::instance().registerUser(user)) {
        QJsonObject response = Protocol::createSuccessResponse("注册成功");
        sendResponse(MSG_REGISTER_RESPONSE, response);
        qDebug() << "用户注册成功:" << user.username;
    } else {
        QJsonObject response = Protocol::createErrorResponse(
            DatabaseManager::instance().lastError());
        sendResponse(MSG_REGISTER_RESPONSE, response);
        qDebug() << "用户注册失败:" << user.username;
    }
}

void ClientHandler::handleGetPatientInfo(const QJsonObject& data) {
    int patientId = data["patientId"].toInt();
    if (patientId == 0) {
        patientId = data["patient_id"].toInt(); // 兼容下划线命名
    }
    if (patientId == 0) {
        patientId = data["user_id"].toInt(); // 兼容user_id
    }
    
    Patient patient;
    if (DatabaseManager::instance().getPatientInfo(patientId, patient)) {
        QJsonObject response = patient.toJson();
        response["success"] = true;
        sendResponse(MSG_GET_PATIENT_INFO_RESPONSE, response);
    } else {
        QJsonObject response = Protocol::createErrorResponse("获取患者信息失败");
        sendResponse(MSG_GET_PATIENT_INFO_RESPONSE, response);
    }
}

void ClientHandler::handleUpdatePatientInfo(const QJsonObject& data) {
    Patient patient = Patient::fromJson(data);
    
    if (DatabaseManager::instance().updatePatientInfo(patient)) {
        QJsonObject response = Protocol::createSuccessResponse("患者信息更新成功");
        sendResponse(MSG_UPDATE_PATIENT_INFO_RESPONSE, response);
        qDebug() << "患者信息更新成功:" << patient.id;
    } else {
        QJsonObject response = Protocol::createErrorResponse(
            DatabaseManager::instance().lastError());
        sendResponse(MSG_UPDATE_PATIENT_INFO_RESPONSE, response);
        qDebug() << "患者信息更新失败:" << patient.id;
    }
}

void ClientHandler::handleMakeAppointment(const QJsonObject& data) {
    Appointment appointment = Appointment::fromJson(data);
    int appointmentId;
    
    // 检查医生是否在预约日期请假
    QDate appointmentDate = appointment.appointmentTime.date();
    if (DatabaseManager::instance().isDoctorOnLeave(appointment.doctorId, appointmentDate)) {
        QJsonObject response = Protocol::createErrorResponse("该医生在此期间请假，请选择其他时间或医生");
        sendResponse(MSG_MAKE_APPOINTMENT_RESPONSE, response);
        qDebug() << "预约失败 - 医生请假 - 医生ID:" << appointment.doctorId << "日期:" << appointmentDate;
        return;
    }
    
    if (DatabaseManager::instance().createAppointment(appointment, appointmentId)) {
        QJsonObject response = Protocol::createSuccessResponse("预约成功");
        response["appointment_id"] = appointmentId;
        sendResponse(MSG_MAKE_APPOINTMENT_RESPONSE, response);
        qDebug() << "预约成功 - 患者ID:" << appointment.patientId << "医生ID:" << appointment.doctorId;
    } else {
        QJsonObject response = Protocol::createErrorResponse("预约失败");
        sendResponse(MSG_MAKE_APPOINTMENT_RESPONSE, response);
        qDebug() << "预约失败";
    }
}

void ClientHandler::handleCancelAppointment(const QJsonObject& data) {
    int appointmentId = data["appointment_id"].toInt();
    
    qDebug() << "收到取消预约请求 - 预约ID:" << appointmentId;
    
    if (DatabaseManager::instance().cancelAppointment(appointmentId)) {
        QJsonObject response = Protocol::createSuccessResponse("预约已取消");
        sendResponse(MSG_CANCEL_APPOINTMENT_RESPONSE, response);
        qDebug() << "预约取消成功 - ID:" << appointmentId;
    } else {
        QJsonObject response = Protocol::createErrorResponse("取消预约失败: " + DatabaseManager::instance().lastError());
        sendResponse(MSG_CANCEL_APPOINTMENT_RESPONSE, response);
        qDebug() << "预约取消失败 - ID:" << appointmentId;
    }
}

void ClientHandler::handleGetAppointments(const QJsonObject& data) {
    int patientId = data["patientId"].toInt();
    if (patientId == 0) {
        patientId = data["patient_id"].toInt(); // 兼容新版本
    }
    
    // 获取线程本地数据库连接
    QSqlDatabase db = DatabaseManager::instance().getThreadDatabase();
    if (!db.isValid()) {
        qDebug() << "无法获取数据库连接";
        QJsonObject response = Protocol::createErrorResponse("数据库连接失败");
        sendResponse(MSG_GET_APPOINTMENTS_RESPONSE, response);
        return;
    }
    
    // 直接使用SQL查询，JOIN获取医生姓名
    QSqlQuery query(db);
    query.prepare("SELECT a.*, u.real_name as doctor_name FROM appointments a "
                 "JOIN users u ON a.doctor_id = u.id "
                 "WHERE a.patient_id = :patientId ORDER BY a.appointment_time DESC");
    query.bindValue(":patientId", patientId);
    
    QJsonArray appointmentsArray;
    if (query.exec()) {
        while (query.next()) {
            QJsonObject apptJson;
            apptJson["id"] = query.value("id").toInt();
            apptJson["patient_id"] = query.value("patient_id").toInt();
            apptJson["doctor_id"] = query.value("doctor_id").toInt();
            apptJson["doctor_name"] = query.value("doctor_name").toString();
            apptJson["appointment_time"] = query.value("appointment_time").toString();
            apptJson["status"] = query.value("status").toString();
            apptJson["symptoms"] = query.value("symptoms").toString();
            appointmentsArray.append(apptJson);
        }
    } else {
        qDebug() << "查询预约失败:" << query.lastError().text();
    }
    
    QJsonObject response;
    response["success"] = true;
    response["appointments"] = appointmentsArray;
    sendResponse(MSG_GET_APPOINTMENTS_RESPONSE, response);
}

void ClientHandler::handleGetAppointmentDetail(const QJsonObject& data) {
    int appointmentId = data["appointment_id"].toInt();
    
    QSqlDatabase db = DatabaseManager::instance().getThreadDatabase();

    
    if (!db.isValid()) {

    
        qDebug() << "无法获取数据库连接";

    
        return;

    
    }

    
    QSqlQuery query(db);
    query.prepare("SELECT a.*, u.real_name as doctor_name, u.phone as doctor_phone "
                 "FROM appointments a "
                 "JOIN users u ON a.doctor_id = u.id "
                 "WHERE a.id = :appointmentId");
    query.bindValue(":appointmentId", appointmentId);
    
    QJsonObject response;
    if (query.exec() && query.next()) {
        QJsonObject appointmentJson;
        appointmentJson["id"] = query.value("id").toInt();
        appointmentJson["patient_id"] = query.value("patient_id").toInt();
        appointmentJson["doctor_id"] = query.value("doctor_id").toInt();
        appointmentJson["doctor_name"] = query.value("doctor_name").toString();
        appointmentJson["doctor_phone"] = query.value("doctor_phone").toString();
        appointmentJson["appointment_time"] = query.value("appointment_time").toString();
        appointmentJson["status"] = query.value("status").toString();
        appointmentJson["symptoms"] = query.value("symptoms").toString();
        
        response["success"] = true;
        response["appointment"] = appointmentJson;
    } else {
        response["success"] = false;
        response["error"] = "未找到预约信息";
    }
    
    sendResponse(MSG_GET_APPOINTMENT_DETAIL_RESPONSE, response);
}

void ClientHandler::handleGetMedicalRecords(const QJsonObject& data) {
    int patientId = data["patientId"].toInt();
    if (patientId == 0) {
        patientId = data["patient_id"].toInt();
    }
    
    QList<MedicalRecord> records = DatabaseManager::instance().getPatientMedicalRecords(patientId);
    
    QJsonArray recordsArray;
    for (const MedicalRecord& record : records) {
        recordsArray.append(record.toJson());
    }
    
    QJsonObject response;
    response["success"] = true;
    response["records"] = recordsArray;
    sendResponse(MSG_GET_MEDICAL_RECORDS_RESPONSE, response);
}

void ClientHandler::handleGetPrescriptions(const QJsonObject& data) {
    QList<Prescription> prescriptions;
    
    // 支持通过 appointment_id 查询
    if (data.contains("appointment_id")) {
        int appointmentId = data["appointment_id"].toInt();
        
        QSqlDatabase db = DatabaseManager::instance().getThreadDatabase();

        
        if (!db.isValid()) {

        
            qDebug() << "无法获取数据库连接";

        
            return;

        
        }

        
        QSqlQuery query(db);
        query.prepare("SELECT * FROM prescriptions WHERE appointment_id = :appointmentId");
        query.bindValue(":appointmentId", appointmentId);
        
        if (query.exec()) {
            while (query.next()) {
                Prescription prescription;
                prescription.id = query.value("id").toInt();
                prescription.medicalRecordId = query.value("medical_record_id").toInt();
                prescription.patientId = query.value("patient_id").toInt();
                prescription.doctorId = query.value("doctor_id").toInt();
                prescription.appointmentId = query.value("appointment_id").toInt();
                prescription.prescriptionTime = query.value("prescription_time").toDateTime();
                prescription.medications = query.value("medications").toString();
                prescription.dosage = query.value("dosage").toString();
                prescription.usage = query.value("usage").toString();
                prescription.frequency = query.value("frequency").toString();
                prescription.days = query.value("days").toInt();
                prescription.notes = query.value("notes").toString();
                prescriptions.append(prescription);
            }
        }
    }
    // 支持通过 medical_record_id 查询
    else if (data.contains("medical_record_id")) {
        int medicalRecordId = data["medical_record_id"].toInt();
        
        QSqlDatabase db = DatabaseManager::instance().getThreadDatabase();

        
        if (!db.isValid()) {

        
            qDebug() << "无法获取数据库连接";

        
            return;

        
        }

        
        QSqlQuery query(db);
        query.prepare("SELECT * FROM prescriptions WHERE medical_record_id = :medicalRecordId");
        query.bindValue(":medicalRecordId", medicalRecordId);
        
        if (query.exec()) {
            while (query.next()) {
                Prescription prescription;
                prescription.id = query.value("id").toInt();
                prescription.medicalRecordId = query.value("medical_record_id").toInt();
                prescription.patientId = query.value("patient_id").toInt();
                prescription.doctorId = query.value("doctor_id").toInt();
                prescription.appointmentId = query.value("appointment_id").toInt();
                prescription.prescriptionTime = query.value("prescription_time").toDateTime();
                prescription.medications = query.value("medications").toString();
                prescription.dosage = query.value("dosage").toString();
                prescription.usage = query.value("usage").toString();
                prescription.frequency = query.value("frequency").toString();
                prescription.days = query.value("days").toInt();
                prescription.notes = query.value("notes").toString();
                prescriptions.append(prescription);
            }
        }
    }
    // 默认通过 patientId 查询
    else {
        int patientId = data["patientId"].toInt();
        if (patientId == 0) {
            patientId = data["patient_id"].toInt();
        }
        
        prescriptions = DatabaseManager::instance().getPatientPrescriptions(patientId);
    }
    
    QJsonArray prescriptionsArray;
    for (const Prescription& prescription : prescriptions) {
        prescriptionsArray.append(prescription.toJson());
    }
    
    QJsonObject response;
    response["success"] = true;
    response["prescriptions"] = prescriptionsArray;
    sendResponse(MSG_GET_PRESCRIPTIONS_RESPONSE, response);
}

void ClientHandler::handleGetDoctorInfo(const QJsonObject& data) {
    int doctorId = data["doctorId"].toInt();
    if (doctorId == 0) {
        doctorId = data["user_id"].toInt(); // 兼容新版本
    }
    
    Doctor doctor;
    if (DatabaseManager::instance().getDoctorInfo(doctorId, doctor)) {
        QJsonObject response = doctor.toJson();
        response["success"] = true;
        sendResponse(MSG_GET_DOCTOR_INFO_RESPONSE, response);
    } else {
        QJsonObject response = Protocol::createErrorResponse("获取医生信息失败");
        sendResponse(MSG_GET_DOCTOR_INFO_RESPONSE, response);
    }
}

void ClientHandler::handleUpdateDoctorInfo(const QJsonObject& data) {
    Doctor doctor = Doctor::fromJson(data);
    
    if (DatabaseManager::instance().updateDoctorInfo(doctor)) {
        QJsonObject response = Protocol::createSuccessResponse("医生信息更新成功");
        sendResponse(MSG_UPDATE_DOCTOR_INFO_RESPONSE, response);
        qDebug() << "医生信息更新成功:" << doctor.id;
    } else {
        QJsonObject response = Protocol::createErrorResponse(
            DatabaseManager::instance().lastError());
        sendResponse(MSG_UPDATE_DOCTOR_INFO_RESPONSE, response);
        qDebug() << "医生信息更新失败:" << doctor.id;
    }
}

void ClientHandler::handleGetDoctorSchedule(const QJsonObject& data) {
    int doctorId = data["doctorId"].toInt();
    if (doctorId == 0) {
        doctorId = data["doctor_id"].toInt();
    }
    QDate date = QDate::fromString(data["date"].toString(), Qt::ISODate);
    
    QList<Appointment> appointments = DatabaseManager::instance().getDoctorAppointments(doctorId, date);
    
    QJsonArray appointmentsArray;
    for (const Appointment& appointment : appointments) {
        appointmentsArray.append(appointment.toJson());
    }
    
    QJsonObject response;
    response["success"] = true;
    response["appointments"] = appointmentsArray;
    sendResponse(MSG_GET_DOCTOR_SCHEDULE_RESPONSE, response);
}

void ClientHandler::handleGetPatientList(const QJsonObject& data) {
    int doctorId = data["doctorId"].toInt();
    if (doctorId == 0) {
        doctorId = data["doctor_id"].toInt(); // 兼容新版本
    }
    
    QDate date = QDate::fromString(data["date"].toString(), "yyyy-MM-dd");
    if (!date.isValid()) {
        date = QDate::fromString(data["date"].toString(), Qt::ISODate);
    }
    
    qDebug() << "获取患者列表 - 医生ID:" << doctorId << "日期:" << date;
    
    // 优化：使用单次JOIN查询替代N+1查询
    QSqlDatabase db = DatabaseManager::instance().getThreadDatabase();

    if (!db.isValid()) {

        qDebug() << "无法获取数据库连接";

        return;

    }

    QSqlQuery query(db);
    query.prepare(
        "SELECT a.id as appointment_id, a.appointment_time, a.status, a.symptoms, "
        "u.id, u.username, u.real_name, u.id_card, u.phone, u.role, "
        "p.gender, p.birth_date, p.address, p.emergency_contact, "
        "p.emergency_phone, p.allergies, p.medical_history "
        "FROM appointments a "
        "JOIN users u ON a.patient_id = u.id "
        "LEFT JOIN patients p ON u.id = p.user_id "
        "WHERE a.doctor_id = :doctorId AND DATE(a.appointment_time) = :date "
        "ORDER BY a.appointment_time"
    );
    query.bindValue(":doctorId", doctorId);
    query.bindValue(":date", date);
    
    QJsonArray patientsArray;
    if (query.exec()) {
        int count = 0;
        while (query.next()) {
            QJsonObject patientData;
            // 预约信息
            patientData["appointment_id"] = query.value("appointment_id").toInt();
            patientData["appointment_time"] = query.value("appointment_time").toString();
            patientData["status"] = query.value("status").toString();
            patientData["symptoms"] = query.value("symptoms").toString();
            
            // 用户基本信息
            patientData["id"] = query.value("id").toInt();
            patientData["username"] = query.value("username").toString();
            patientData["real_name"] = query.value("real_name").toString();
            patientData["id_card"] = query.value("id_card").toString();
            patientData["phone"] = query.value("phone").toString();
            patientData["role"] = query.value("role").toInt();
            
            // 患者详细信息
            patientData["gender"] = query.value("gender").toString();
            patientData["birth_date"] = query.value("birth_date").toString();
            patientData["address"] = query.value("address").toString();
            patientData["emergency_contact"] = query.value("emergency_contact").toString();
            patientData["emergency_phone"] = query.value("emergency_phone").toString();
            patientData["allergies"] = query.value("allergies").toString();
            patientData["medical_history"] = query.value("medical_history").toString();
            
            patientsArray.append(patientData);
            count++;
        }
        qDebug() << "  查询成功，返回" << count << "条记录";
    } else {
        qDebug() << "  查询失败:" << query.lastError().text();
    }
    
    QJsonObject response;
    response["success"] = true;
    response["patients"] = patientsArray;
    sendResponse(MSG_GET_PATIENT_LIST_RESPONSE, response);
}

void ClientHandler::handleCreateMedicalRecord(const QJsonObject& data) {
    MedicalRecord record = MedicalRecord::fromJson(data);
    int recordId;
    
    if (DatabaseManager::instance().createMedicalRecord(record, recordId)) {
        QJsonObject response = Protocol::createSuccessResponse("创建病历成功");
        response["recordId"] = recordId;
        sendResponse(MSG_CREATE_MEDICAL_RECORD_RESPONSE, response);
    } else {
        QJsonObject response = Protocol::createErrorResponse("创建病历失败");
        sendResponse(MSG_CREATE_MEDICAL_RECORD_RESPONSE, response);
    }
}

void ClientHandler::handleCreatePrescription(const QJsonObject& data) {
    Prescription prescription = Prescription::fromJson(data);
    
    if (DatabaseManager::instance().createPrescription(prescription)) {
        sendResponse(MSG_CREATE_PRESCRIPTION_RESPONSE, 
                    Protocol::createSuccessResponse("开具处方成功"));
    } else {
        sendResponse(MSG_CREATE_PRESCRIPTION_RESPONSE, 
                    Protocol::createErrorResponse("开具处方失败"));
    }
}

void ClientHandler::handleCreateExamRequest(const QJsonObject& data) {
    ExamRequest exam = ExamRequest::fromJson(data);
    
    if (DatabaseManager::instance().createExamRequest(exam)) {
        sendResponse(MSG_CREATE_EXAM_REQUEST_RESPONSE, 
                    Protocol::createSuccessResponse("开具检查单成功"));
    } else {
        sendResponse(MSG_CREATE_EXAM_REQUEST_RESPONSE, 
                    Protocol::createErrorResponse("开具检查单失败"));
    }
}

void ClientHandler::handleGetDepartments(const QJsonObject& data) {
    Q_UNUSED(data);
    
    QList<Department> departments = DatabaseManager::instance().getAllDepartments();
    
    QJsonArray deptArray;
    for (const Department& dept : departments) {
        deptArray.append(dept.toJson());
    }
    
    QJsonObject response;
    response["success"] = true;
    response["departments"] = deptArray;
    sendResponse(MSG_GET_DEPARTMENTS_RESPONSE, response);
}

void ClientHandler::handleGetDoctorsByDept(const QJsonObject& data) {
    int departmentId = data["departmentId"].toInt();
    if (departmentId == 0) {
        departmentId = data["department_id"].toInt();
    }
    
    QString clinicType = data["clinic_type"].toString();
    QString doctorName = data["doctor_name"].toString();
    
    // 构建SQL查询，支持门诊类型和医生姓名筛选
    QString sql = "SELECT u.*, d.*, dep.name as dept_name FROM users u "
                  "JOIN doctors d ON u.id = d.user_id "
                  "JOIN departments dep ON d.department_id = dep.id "
                  "WHERE d.department_id = :departmentId";
    
    if (!clinicType.isEmpty()) {
        sql += " AND d.clinic_type = :clinicType";
    }
    if (!doctorName.isEmpty()) {
        sql += " AND u.real_name LIKE :doctorName";
    }
    
    QSqlDatabase db = DatabaseManager::instance().getThreadDatabase();

    
    if (!db.isValid()) {

    
        qDebug() << "无法获取数据库连接";

    
        return;

    
    }

    
    QSqlQuery query(db);
    query.prepare(sql);
    query.bindValue(":departmentId", departmentId);
    if (!clinicType.isEmpty()) {
        query.bindValue(":clinicType", clinicType);
    }
    if (!doctorName.isEmpty()) {
        query.bindValue(":doctorName", "%" + doctorName + "%");
    }
    
    QJsonArray doctorsArray;
    if (query.exec()) {
        while (query.next()) {
            Doctor doctor;
            doctor.id = query.value("id").toInt();
            doctor.username = query.value("username").toString();
            doctor.realName = query.value("real_name").toString();
            doctor.phone = query.value("phone").toString();
            doctor.departmentId = query.value("department_id").toInt();
            doctor.departmentName = query.value("dept_name").toString();
            doctor.title = query.value("title").toString();
            doctor.specialty = query.value("specialty").toString();
            doctor.education = query.value("education").toString();
            doctor.experience = query.value("experience").toInt();
            doctor.introduction = query.value("introduction").toString();
            doctor.workTime = query.value("work_time").toString();
            doctor.consultationFee = query.value("consultation_fee").toDouble();
            doctor.dailyPatientLimit = query.value("daily_patient_limit").toInt();
            doctor.clinicType = query.value("clinic_type").toString();
            
            // 统计今天的已预约人数
            QSqlQuery countQuery;
            countQuery.prepare("SELECT COUNT(*) as count FROM appointments "
                             "WHERE doctor_id = :doctorId AND DATE(appointment_time) = CURDATE() "
                             "AND status != '已取消'");
            countQuery.bindValue(":doctorId", doctor.id);
            
            if (countQuery.exec() && countQuery.next()) {
                doctor.bookedCount = countQuery.value("count").toInt();
            } else {
                doctor.bookedCount = 0;
            }
            
            // 计算剩余预约数
            doctor.remainingSlots = doctor.dailyPatientLimit - doctor.bookedCount;
            if (doctor.remainingSlots < 0) {
                doctor.remainingSlots = 0;
            }
            
            doctorsArray.append(doctor.toJson());
        }
    }
    
    QJsonObject response;
    response["success"] = true;
    response["doctors"] = doctorsArray;
    sendResponse(MSG_GET_DOCTORS_BY_DEPT_RESPONSE, response);
}

void ClientHandler::handlePayment(const QJsonObject& data) {
    Payment payment = Payment::fromJson(data);
    
    if (DatabaseManager::instance().createPayment(payment)) {
        sendResponse(MSG_PAYMENT_RESPONSE, Protocol::createSuccessResponse("缴费成功"));
    } else {
        sendResponse(MSG_PAYMENT_RESPONSE, Protocol::createErrorResponse("缴费失败"));
    }
}

void ClientHandler::handleGetPaymentHistory(const QJsonObject& data) {
    int patientId = data["patientId"].toInt();
    if (patientId == 0) {
        patientId = data["patient_id"].toInt();
    }
    
    QList<Payment> payments = DatabaseManager::instance().getPatientPayments(patientId);
    
    QJsonArray paymentsArray;
    for (const Payment& payment : payments) {
        paymentsArray.append(payment.toJson());
    }
    
    QJsonObject response;
    response["success"] = true;
    response["payments"] = paymentsArray;
    sendResponse(MSG_GET_PAYMENT_HISTORY_RESPONSE, response);
}

void ClientHandler::handleStartConsultation(const QJsonObject& data) {
    int appointmentId = data["appointment_id"].toInt();
    
    // 更新预约状态为"就诊中"
    if (DatabaseManager::instance().updateAppointmentStatus(appointmentId, "就诊中")) {
        QJsonObject response;
        response["success"] = true;
        response["message"] = "开始接诊成功";
        sendResponse(MSG_START_CONSULTATION_RESPONSE, response);
    } else {
        sendResponse(MSG_START_CONSULTATION_RESPONSE, 
                    Protocol::createErrorResponse("开始接诊失败"));
    }
}

void ClientHandler::handleFinishConsultation(const QJsonObject& data) {
    int appointmentId = data["appointment_id"].toInt();
    
    qDebug() << "=== 完成就诊请求 ===";
    qDebug() << "预约ID:" << appointmentId;
    
    // 检查是否已完成病历和处方
    bool hasRecord = false, hasPrescription = false;
    DatabaseManager::instance().checkAppointmentCompletion(appointmentId, hasRecord, hasPrescription);
    
    qDebug() << "检查结果 - 病历:" << hasRecord << "处方:" << hasPrescription;
    
    if (!hasRecord || !hasPrescription) {
        QString message;
        if (!hasRecord && !hasPrescription) {
            message = "请先创建病历并开具处方！";
        } else if (!hasRecord) {
            message = "请先创建病历！";
        } else {
            message = "请先开具处方！";
        }
        
        qDebug() << "完成就诊被拒绝:" << message;
        
        QJsonObject response;
        response["success"] = false;
        response["message"] = message;
        sendResponse(MSG_FINISH_CONSULTATION_RESPONSE, response);
        return;
    }
    
    qDebug() << "允许完成就诊";
    
    // 更新预约状态为"已就诊"
    if (DatabaseManager::instance().updateAppointmentStatus(appointmentId, "已就诊")) {
        QJsonObject response;
        response["success"] = true;
        response["message"] = "就诊完成";
        sendResponse(MSG_FINISH_CONSULTATION_RESPONSE, response);
    } else {
        sendResponse(MSG_FINISH_CONSULTATION_RESPONSE, 
                    Protocol::createErrorResponse("完成就诊失败"));
    }
}

void ClientHandler::handleCheckAppointmentCompletion(const QJsonObject& data) {
    int appointmentId = data["appointment_id"].toInt();
    
    bool hasRecord = false, hasPrescription = false;
    DatabaseManager::instance().checkAppointmentCompletion(appointmentId, hasRecord, hasPrescription);
    
    QJsonObject response;
    response["success"] = true;
    response["has_record"] = hasRecord;
    response["has_prescription"] = hasPrescription;
    sendResponse(MSG_CHECK_APPOINTMENT_COMPLETION_RESPONSE, response);
}

// 医患沟通相关实现
void ClientHandler::handleGetAllDoctors(const QJsonObject& data) {
    qDebug() << "服务端 - 处理获取所有医生请求";
    QList<Doctor> doctors = DatabaseManager::instance().getAllDoctors();
    qDebug() << "  查询到医生数量:" << doctors.size();
    
    QJsonArray doctorsArray;
    for (const Doctor& doctor : doctors) {
        doctorsArray.append(doctor.toJson());
        qDebug() << "    医生:" << doctor.realName << "科室ID:" << doctor.departmentId;
    }
    
    QJsonObject response;
    response["success"] = true;
    response["doctors"] = doctorsArray;
    sendResponse(MSG_GET_ALL_DOCTORS_RESPONSE, response);
    qDebug() << "  已发送响应，医生数组大小:" << doctorsArray.size();
}

void ClientHandler::handleGetChatPatients(const QJsonObject& data) {
    int doctorId = data["doctor_id"].toInt();
    
    QList<Patient> patients = DatabaseManager::instance().getChatPatients(doctorId);
    
    QJsonArray patientsArray;
    for (const Patient& patient : patients) {
        QJsonObject patientJson = patient.toJson();
        // 添加未读消息数
        int unreadCount = DatabaseManager::instance().getUnreadCount(doctorId, patient.id);
        patientJson["unread_count"] = unreadCount;
        patientsArray.append(patientJson);
    }
    
    QJsonObject response;
    response["success"] = true;
    response["patients"] = patientsArray;
    sendResponse(MSG_GET_CHAT_PATIENTS_RESPONSE, response);
}

void ClientHandler::handleSendMessage(const QJsonObject& data) {
    Message msg = Message::fromJson(data);
    msg.sendTime = QDateTime::currentDateTime();
    msg.isRead = false;
    
    if (DatabaseManager::instance().sendMessage(msg)) {
        QJsonObject response;
        response["success"] = true;
        response["message"] = "消息发送成功";
        sendResponse(MSG_SEND_MESSAGE_RESPONSE, response);
    } else {
        sendResponse(MSG_SEND_MESSAGE_RESPONSE, 
                    Protocol::createErrorResponse("消息发送失败"));
    }
}

void ClientHandler::handleGetChatHistory(const QJsonObject& data) {
    int userId1 = data["user_id1"].toInt();
    int userId2 = data["user_id2"].toInt();
    
    QList<Message> messages = DatabaseManager::instance().getChatHistory(userId1, userId2);
    
    QJsonArray messagesArray;
    for (const Message& msg : messages) {
        messagesArray.append(msg.toJson());
    }
    
    QJsonObject response;
    response["success"] = true;
    response["messages"] = messagesArray;
    sendResponse(MSG_GET_CHAT_HISTORY_RESPONSE, response);
}

void ClientHandler::handleGetUnreadCount(const QJsonObject& data) {
    int receiverId = data["receiver_id"].toInt();
    int senderId = data.contains("sender_id") ? data["sender_id"].toInt() : 0;
    
    int count = DatabaseManager::instance().getUnreadCount(receiverId, senderId);
    
    QJsonObject response;
    response["success"] = true;
    response["unread_count"] = count;
    sendResponse(MSG_GET_UNREAD_COUNT_RESPONSE, response);
}

void ClientHandler::handleMarkAsRead(const QJsonObject& data) {
    int receiverId = data["receiver_id"].toInt();
    int senderId = data["sender_id"].toInt();
    
    if (DatabaseManager::instance().markAsRead(receiverId, senderId)) {
        QJsonObject response;
        response["success"] = true;
        sendResponse(MSG_MARK_AS_READ_RESPONSE, response);
    } else {
        sendResponse(MSG_MARK_AS_READ_RESPONSE, 
                    Protocol::createErrorResponse("标记已读失败"));
    }
}

// 考勤管理相关实现
void ClientHandler::handleAttendanceCheckIn(const QJsonObject& data) {
    int doctorId = data["doctor_id"].toInt();
    
    if (DatabaseManager::instance().checkIn(doctorId)) {
        QJsonObject response;
        response["success"] = true;
        response["message"] = "打卡成功！！！";
        sendResponse(MSG_ATTENDANCE_CHECKIN_RESPONSE, response);
    } else {
        sendResponse(MSG_ATTENDANCE_CHECKIN_RESPONSE, 
                    Protocol::createErrorResponse(DatabaseManager::instance().lastError()));
    }
}

void ClientHandler::handleAttendanceCancel(const QJsonObject& data) {
    int doctorId = data["doctor_id"].toInt();
    QDate date = QDate::fromString(data["date"].toString(), "yyyy-MM-dd");
    
    if (DatabaseManager::instance().cancelCheckIn(doctorId, date)) {
        QJsonObject response;
        response["success"] = true;
        response["message"] = "打卡已取消";
        sendResponse(MSG_ATTENDANCE_CANCEL_RESPONSE, response);
    } else {
        sendResponse(MSG_ATTENDANCE_CANCEL_RESPONSE, 
                    Protocol::createErrorResponse("取消打卡失败"));
    }
}

void ClientHandler::handleGetAttendanceRecords(const QJsonObject& data) {
    int doctorId = data["doctor_id"].toInt();
    QDate startDate = QDate::fromString(data["start_date"].toString(), "yyyy-MM-dd");
    QDate endDate = QDate::fromString(data["end_date"].toString(), "yyyy-MM-dd");
    
    QList<AttendanceRecord> records = DatabaseManager::instance().getAttendanceRecords(doctorId, startDate, endDate);
    
    QJsonArray recordsArray;
    for (const AttendanceRecord& record : records) {
        recordsArray.append(record.toJson());
    }
    
    QJsonObject response;
    response["success"] = true;
    response["records"] = recordsArray;
    sendResponse(MSG_GET_ATTENDANCE_RECORDS_RESPONSE, response);
}

void ClientHandler::handleGetTodayAttendance(const QJsonObject& data) {
    int doctorId = data["doctor_id"].toInt();
    
    AttendanceRecord record;
    bool hasAttendance = DatabaseManager::instance().getTodayAttendance(doctorId, record);
    
    QJsonObject response;
    response["success"] = true;
    response["has_attendance"] = hasAttendance;
    if (hasAttendance) {
        response["record"] = record.toJson();
    }
    sendResponse(MSG_GET_TODAY_ATTENDANCE_RESPONSE, response);
}

void ClientHandler::handleCreateLeaveRequest(const QJsonObject& data) {
    LeaveRequest request = LeaveRequest::fromJson(data);
    
    // 检查请假期间是否有预约
    QList<Appointment> conflictAppointments = DatabaseManager::instance().getDoctorAppointmentsInRange(
        request.doctorId, request.startDate, request.endDate);
    
    if (DatabaseManager::instance().createLeaveRequest(request)) {
        QJsonObject response;
        response["success"] = true;
        
        // 自动取消请假期间的所有预约
        int canceledCount = 0;
        if (!conflictAppointments.isEmpty()) {
            if (DatabaseManager::instance().cancelAppointmentsInRange(
                request.doctorId, request.startDate, request.endDate)) {
                canceledCount = conflictAppointments.size();
                qDebug() << "自动取消预约数量:" << canceledCount;
            }
        }
        
        // 返回提示信息
        if (canceledCount > 0) {
            QString successMsg = QString("请假申请已批准！系统已自动取消 %1 至 %2 期间的 %3 个预约。")
                .arg(request.startDate.toString("yyyy-MM-dd"))
                .arg(request.endDate.toString("yyyy-MM-dd"))
                .arg(canceledCount);
            response["message"] = successMsg;
            response["canceled_count"] = canceledCount;
        } else {
            response["message"] = "请假申请已批准！";
            response["canceled_count"] = 0;
        }
        
        sendResponse(MSG_CREATE_LEAVE_REQUEST_RESPONSE, response);
    } else {
        sendResponse(MSG_CREATE_LEAVE_REQUEST_RESPONSE, 
                    Protocol::createErrorResponse(DatabaseManager::instance().lastError()));
    }
}

void ClientHandler::handleCancelLeaveRequest(const QJsonObject& data) {
    int requestId = data["request_id"].toInt();
    
    if (DatabaseManager::instance().cancelLeaveRequest(requestId)) {
        QJsonObject response;
        response["success"] = true;
        response["message"] = "取消成功！";
        sendResponse(MSG_CANCEL_LEAVE_REQUEST_RESPONSE, response);
    } else {
        sendResponse(MSG_CANCEL_LEAVE_REQUEST_RESPONSE, 
                    Protocol::createErrorResponse("取消请假失败"));
    }
}

void ClientHandler::handleGetLeaveRequests(const QJsonObject& data) {
    int doctorId = data["doctor_id"].toInt();
    
    QList<LeaveRequest> requests = DatabaseManager::instance().getLeaveRequests(doctorId);
    
    QJsonArray requestsArray;
    for (const LeaveRequest& request : requests) {
        requestsArray.append(request.toJson());
    }
    
    QJsonObject response;
    response["success"] = true;
    response["requests"] = requestsArray;
    sendResponse(MSG_GET_LEAVE_REQUESTS_RESPONSE, response);
}

void ClientHandler::handleCancelLeave(const QJsonObject& data) {
    int requestId = data["request_id"].toInt();
    
    if (DatabaseManager::instance().cancelLeave(requestId)) {
        QJsonObject response;
        response["success"] = true;
        response["message"] = "销假成功";
        sendResponse(MSG_CANCEL_LEAVE_RESPONSE, response);
    } else {
        sendResponse(MSG_CANCEL_LEAVE_RESPONSE, 
                    Protocol::createErrorResponse("销假失败"));
    }
}

void ClientHandler::handleGetPopularMedicines(const QJsonObject& data) {
    Q_UNUSED(data);
    
    QList<Medicine> medicines = DatabaseManager::instance().getPopularMedicines();
    
    QJsonArray medicineArray;
    for (const Medicine& medicine : medicines) {
        medicineArray.append(medicine.toJson());
    }
    
    QJsonObject response;
    response["success"] = true;
    response["medicines"] = medicineArray;
    sendResponse(MSG_GET_POPULAR_MEDICINES_RESPONSE, response);
}

void ClientHandler::handleSearchMedicines(const QJsonObject& data) {
    QString keyword = data["keyword"].toString();
    
    QList<Medicine> medicines = DatabaseManager::instance().searchMedicines(keyword);
    
    QJsonArray medicineArray;
    for (const Medicine& medicine : medicines) {
        medicineArray.append(medicine.toJson());
    }
    
    QJsonObject response;
    response["success"] = true;
    response["medicines"] = medicineArray;
    sendResponse(MSG_SEARCH_MEDICINES_RESPONSE, response);
}

void ClientHandler::handleGetNotifications(const QJsonObject& data) {
    Q_UNUSED(data);
    if (m_currentUserId == 0) {
        sendResponse(MSG_ERROR, Protocol::createErrorResponse("未登录"));
        return;
    }
    QList<Notification> notifications = DatabaseManager::instance().getUserNotifications(m_currentUserId, m_currentUserRole);
    QJsonArray notificationArray;
    for (const Notification& notification : notifications) {
        notificationArray.append(notification.toJson());
    }
    QJsonObject response;
    response["success"] = true;
    response["notifications"] = notificationArray;
    sendResponse(MSG_GET_NOTIFICATIONS_RESPONSE, response);
}

void ClientHandler::handleClearAllNotifications(const QJsonObject& data) {
    Q_UNUSED(data);
    if (m_currentUserId == 0) {
        sendResponse(MSG_ERROR, Protocol::createErrorResponse("未登录"));
        return;
    }
    if (DatabaseManager::instance().clearAllNotifications(m_currentUserId, m_currentUserRole)) {
        QJsonObject response = Protocol::createSuccessResponse("已清空所有通知");
        sendResponse(MSG_CLEAR_ALL_NOTIFICATIONS_RESPONSE, response);
    } else {
        sendResponse(MSG_ERROR, Protocol::createErrorResponse("清空通知失败"));
    }
}

